package org.apache.rocketmq.example.quickstart.sort;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 顺序消费者
 */
public class InOrderConsumer {
    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group-3");
        consumer.setNamesrvAddr("39.107.66.31:9876");
        consumer.subscribe("message-topic-6", "*");
        // 指定消费偏移量
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        // 指定消费监听器
        consumer.registerMessageListener(new RegisterMessageListener());
        // 启动消费者
        consumer.start();
        System.out.println("消费者已启动");
    }

    // 构建消费监听器 - 顺序监听器
    private static class RegisterMessageListener implements MessageListenerOrderly {
        @Override
        public ConsumeOrderlyStatus consumeMessage(List<MessageExt> messageExtList, ConsumeOrderlyContext context) {
            context.setAutoCommit(true);
            for (MessageExt messageExt : messageExtList) {
                try {
                    System.out.println("QueueId:" + messageExt.getQueueId() + " , body:"  + new String(messageExt.getBody(), "UTF-8"));
                } catch (Exception e) {
                    System.out.println("消费异常：" + e);
                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                }
            }
            return ConsumeOrderlyStatus.SUCCESS;
        }
    }
}
